package ctrl.action.impl;

import java.io.IOException;
import java.security.InvalidParameterException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import model.beans.ItemBean;
import model.beans.ShoppingCartBean;
import model.beans.ShoppingCartItemBean;

import util.ProjectConstants;

import ctrl.action.ServletAction;

public class ShoppingCartServletAction implements ServletAction{
	ServletContext context;

	public ShoppingCartServletAction(ServletContext context){
		this.context = context;
	}

	@Override
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException{
		
		String jsp = null;
		String jspRedirect = null;
		HttpSession session = request.getSession();
		// retrieve model from context
		Model model = (Model) request.getServletContext().getAttribute(ProjectConstants.PARAMMODEL);


		// retrieve shopping cart from session, if not exits, create a new shopping cart
		ShoppingCartBean cart = (ShoppingCartBean) session.getAttribute(ProjectConstants.PARAMMYCART);

		// instantiate shopping cart and put it into session
		if (cart == null){
			cart = model.createShoppingCart();
			session.setAttribute(ProjectConstants.PARAMMYCART, cart);			
		}				
		
		// process Add to Cart Action
		if (request.getParameter(ProjectConstants.PARAMADDTOCART) != null){			
			doAddToCart(request, response, model, cart);
			session.setAttribute(ProjectConstants.PARAMMYCART, cart);
			jsp = ProjectConstants.PAGESHOPPINGCART;
		}
		// process Update Cart Action
		else if (request.getParameter(ProjectConstants.PARAMUPDATE) != null){			
			doUpdateCart(request,response, model, cart);			
			jsp = ProjectConstants.PAGESHOPPINGCART;
		}
		// process Clear Cart Action
		else if (request.getParameter(ProjectConstants.PARAMCLEARCART) != null){
			cart = model.createShoppingCart();
			session.setAttribute(ProjectConstants.PARAMMYCART, cart);
			jsp = ProjectConstants.PAGESHOPPINGCART;
		}
		// process Continue Shopping Action
		else if (request.getParameter(ProjectConstants.PARAMCONTINUESHOPPING) != null){
			jsp = ProjectConstants.PAGEHOME;
		}
		// process Check out Action
		else if (request.getParameter(ProjectConstants.PARAMPROCEEDTOCHECKOUT) != null){
			jspRedirect = ProjectConstants.PAGECHECKOUT;
		}
		else{
			// display the shopping cart
			jsp = ProjectConstants.PAGESHOPPINGCART;
		}
		

		// For returning page after login
		session.setAttribute(ProjectConstants.PARAMPREVIOUSPAGE,ProjectConstants.PARAMSHOPPINGCART);
		
		if(jsp != null){
			context.getRequestDispatcher("/" + jsp + ".jspx").forward(request,response);
		}
		else{
			response.sendRedirect(context.getContextPath()+ "/" + jspRedirect);
		}
	}

	public void doAddToCart(HttpServletRequest request,
			HttpServletResponse response, Model model, ShoppingCartBean cart) throws IOException,
			ServletException{
		// retrieve the form data
		String itemNumber = request.getParameter(ProjectConstants.PARAMITEM);
		String qty = request.getParameter(ProjectConstants.PARAMQUANTITY);

		// retrieve itemBean
		ItemBean item = model.getItemByNumber(itemNumber);

		// instantiate shoppingItemBean
		ShoppingCartItemBean shoppingCartItem = new ShoppingCartItemBean();
		try{
			shoppingCartItem.setItem(item);
			shoppingCartItem.setQuantity(cart.validateItemQuantity(qty));
						
			// add the shoppingCartitem to the cart
			cart.addItem(shoppingCartItem);
			request.setAttribute(ProjectConstants.PARAMMESSAGE, "Item is added to the cart!");			
		}
		catch (InvalidParameterException e)	{
			request.setAttribute(ProjectConstants.PARAMERRORMESSAGE, " Invalid quantity!");
			throw new InvalidParameterException();
		}
		catch (NumberFormatException e)	{
			request.setAttribute(ProjectConstants.PARAMERRORMESSAGE, "Quantity must be a number!");
			throw new NumberFormatException();
		}
		
	}
	
	public void doUpdateCart(HttpServletRequest request,
			HttpServletResponse response, Model model, ShoppingCartBean cart) throws IOException,
			ServletException{
		// retrieve form data;			
		for ( String key: cart.getItemsMap().keySet() )	{
			try {
				int qty = Integer.parseInt(request.getParameter(key));
				// update the shopping cart	
				cart.updateItem(key, qty);				
			
				request.setAttribute(ProjectConstants.PARAMMESSAGE, "Your cart is updated!");
			}
			catch (InvalidParameterException e)
			{
				request.setAttribute(ProjectConstants.PARAMERRORMESSAGE, " Invalid quantity!");
			}
			catch (NumberFormatException e)
			{
				request.setAttribute(ProjectConstants.PARAMERRORMESSAGE, "Quantity must be a number!");
			}
		}		
	}

}
